import React from 'react';
import {
  View,
  Text,
  FlatList,
  RefreshControl,
  StyleSheet,
  TouchableOpacity,
  useColorScheme,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useAppContext } from '../context/AppContext';
import { useRefresh } from '../hooks';
import { News, TabScreenProps } from '../types';

type NewsScreenProps = TabScreenProps<'News'>;

const NewsScreen: React.FC<NewsScreenProps> = () => {
  const isDarkMode = useColorScheme() === 'dark';
  const { state: { news } } = useAppContext();
  const { refreshing, refreshNews } = useRefresh();

  const navigation = useNavigation();

  const handleNewsPress = (newsItem: News) => {
    navigation.navigate('NewsDetail' as never, { news: newsItem } as never);
  };

  const renderNewsItem = ({ item }: { item: News }) => (
    <TouchableOpacity 
      style={styles.newsItem}
      onPress={() => handleNewsPress(item)}
    >
      <Text style={[styles.newsTitle, isDarkMode && styles.lightText]}>
        {item.title}
      </Text>
      <Text style={[styles.newsContent, isDarkMode && styles.lightText]}>
        {item.content}
      </Text>
      <Text style={styles.newsTime}>{item.publishTime}</Text>
    </TouchableOpacity>
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={news}
        keyExtractor={(item) => item.id}
        renderItem={renderNewsItem}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={refreshNews} />
        }
        ListEmptyComponent={
          <Text style={[styles.emptyText, isDarkMode && styles.lightText]}>
            暂无资讯，下拉刷新获取最新内容
          </Text>
        }
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.listContent}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  listContent: {
    paddingBottom: 40,
  },
  pageTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    color: '#000',
  },
  lightText: {
    color: '#fff',
  },
  newsItem: {
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 8,
    marginBottom: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  newsTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  newsContent: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
    marginBottom: 8,
  },
  newsTime: {
    fontSize: 12,
    color: '#999',
  },
  emptyText: {
    textAlign: 'center',
    marginTop: 50,
    color: '#888',
    fontSize: 16,
  },
});

export default NewsScreen;